<template>
  <el-card shadow="hover">
    <el-table
      :data="catrgoryList"
      border
      :row-key="getRowKey"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="分类ID" prop="id" width="200" align="center" />
      <el-table-column label="分类名称" prop="name" />
      <el-table-column label="操作" width="400" align="center">
        <el-button type="primary" :icon="Plus" size="small" />
        <el-button type="warning" :icon="Edit" size="small" />
        <el-button type="danger" :icon="Delete" size="small" />
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CCategory",
};
</script>

<script lang="ts" setup>
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from "@/api/product/category";
import type {
  CategoryList,
  categoryItme,
} from "@/api/product/model/categoryModel";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { onMounted, ref } from "vue";

const catrgoryList = ref<CategoryList>([]);

onMounted(async () => {
  const res = await getCategory1ListApi();
  catrgoryList.value = res.map((item) => {
    return {
      ...item,
      hasChildren: true,
      level: 1,
    };
  });
});

const load = async (
  row: categoryItme,
  treeNode: unknown,
  resolve: (data: CategoryList) => void
) => {
  if (row.level === 1) {
    const res = await getCategory2ListApi(row.id);
    resolve(
      res.map((item) => {
        return {
          ...item,
          hasChildren: true,
          level: 2,
        };
      })
    );
  } else if (row.level === 2) {
    const res = await getCategory3ListApi(row.id);
    resolve(
      res.map((item) => {
        return {
          ...item,
          level: 3,
        };
      })
    );
  }
};

// 设置元素key
const getRowKey = (row: categoryItme) => {
  return row.level + "" + row.id;
};
</script>

<style scoped></style>
